﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.Logging;
using RotovapPlatform.Application.Services;
using RotovapPlatform.Application.Services.Devices;
using RotovapPlatform.Application.Services.Experiments;
using RotovapPlatform.Application.Services.Scheduling;
using RotovapPlatform.Domain.Business.Machine.Enums;
using RotovapPlatform.Domain.Business.Recipes.Entities;
using RotovapPlatform.Domain.Business.Recipes.Entities.Parameters;
using RotovapPlatform.Domain.Equipment.Interfaces.Services;
using RotovapPlatform.Domain.Services.DeviceParameters;
using RotovapPlatform.Domain.Services.Experiments;
using RotovapPlatform.UI.Services;
using System.Collections.Generic;
using RotovapPlatform.Domain.Services.Devices;
using RotovapPlatform.Domain.Services.Scheduling;
using static RotovapPlatform.Domain.Business.Machine.Enums.ExperimentConfigEnums;
using RotovapPlatform.Domain.Business.Interfaces;
using RotovapPlatform.Domain.Common;
using RotovapPlatform.Domain.Equipment.Device.OilBath.Dto;
using RotovapPlatform.Domain.Equipment.Device.TCU.Dto;
using System.Threading;
using System.Threading.Tasks;
using RotovapPlatform.Domain.Equipment.Device.Motors.Dto;

namespace RotovapPlatform.UI.ViewModels.ExperimentManagement
{
	/// <summary>
	/// 主运行界面视图模型
	/// </summary>
	public partial class MainOperationViewModel : ObservableObject, IDisposable
	{
		private readonly ILogger<MainOperationViewModel> _logger;
		private readonly IRecipeAppService _recipeAppService;
		private readonly IMessageService _messageService;
		private readonly IDeviceParameterDomainService _deviceParameterService;
		private readonly ITaskSchedulingAppService _taskSchedulingAppService;
		private readonly IDeviceAppService _deviceAppService;
		private readonly IExperimentProcessAppService _experimentProcessAppService;
		private readonly IExperimentRepository _experimentRepository;
		private readonly IDeviceStatusService _deviceStatusService;
		private bool _isDisposed = false;
		private bool _isMonitoring = false;
		private CancellationTokenSource _statusUpdateCts;

		#region 属性

		/// <summary>
		/// 当前实验ID
		/// </summary>
		[ObservableProperty]
		private Guid? _currentExperimentId;

		/// <summary>
		/// 当前实验阶段
		/// </summary>
		[ObservableProperty]
		private ExperimentStage? _currentExperimentStage;

		/// <summary>
		/// 当前实验子阶段
		/// </summary>
		[ObservableProperty]
		private ExperimentSubStage? _currentExperimentSubStage;

		/// <summary>
		/// 当前阶段进度百分比
		/// </summary>
		[ObservableProperty]
		private int _currentStageProgress = 0;

		/// <summary>
		/// 实验组列表
		/// </summary>
		[ObservableProperty]
		private ObservableCollection<ExperimentGroupViewModel> _experimentGroups = new ObservableCollection<ExperimentGroupViewModel>();

		/// <summary>
		/// 选中的实验组
		/// </summary>
		[ObservableProperty]
		private ExperimentGroupViewModel _selectedExperimentGroup;

		/// <summary>
		/// 选中的实验
		/// </summary>
		[ObservableProperty]
		private ExperimentViewModel _selectedExperiment;

		/// <summary>
		/// 设备模式
		/// </summary>
		[ObservableProperty]
		private DeviceEnums.DeviceMode _deviceMode = DeviceEnums.DeviceMode.Manual;

		/// <summary>
		/// 设备模式变更处理
		/// </summary>
		partial void OnDeviceModeChanged(DeviceEnums.DeviceMode value)
		{
			_logger.LogInformation($"设备模式已在UI中更新为: {value}");
		}

		/// <summary>
		/// 设备状态
		/// </summary>
		[ObservableProperty]
		private DeviceEnums.DeviceStatus _deviceStatus = DeviceEnums.DeviceStatus.Idle;

		/// <summary>
		/// 设备状态变更处理
		/// </summary>
		partial void OnDeviceStatusChanged(DeviceEnums.DeviceStatus value)
		{
			_logger.LogInformation($"设备状态已在UI中更新为: {value}");
			// 更新按钮状态
			OnPropertyChanged(nameof(CanRun));
			OnPropertyChanged(nameof(CanPause));
			OnPropertyChanged(nameof(CanResume));
			OnPropertyChanged(nameof(CanReset));
			OnPropertyChanged(nameof(CanInitialize));
			OnPropertyChanged(nameof(RunningState));

			// 确保命令重新评估可执行状态
			RunCommand.NotifyCanExecuteChanged();
			PauseCommand.NotifyCanExecuteChanged();
			ResumeCommand.NotifyCanExecuteChanged();
			ResetCommand.NotifyCanExecuteChanged();
			InitializeDevicesCommand.NotifyCanExecuteChanged();
		}

		/// <summary>
		/// 当前步骤
		/// </summary>
		[ObservableProperty]
		private DeviceEnums.MainStep _currentStep = DeviceEnums.MainStep.None;

		/// <summary>
		/// 是否正在运行
		/// </summary>
		[ObservableProperty]
		private bool _isRunning = false;

		/// <summary>
		/// 是否已暂停
		/// </summary>
		[ObservableProperty]
		private bool _isPaused = false;

		/// <summary>
		/// 是否正在加载
		/// </summary>
		[ObservableProperty]
		private bool _isLoading = false;

		/// <summary>
		/// 进度
		/// </summary>
		[ObservableProperty]
		private double _progress = 0;

		/// <summary>
		/// 剩余时间（分钟）
		/// </summary>
		[ObservableProperty]
		private int _remainingTime = 0;

		/// <summary>
		/// 油浴温度
		/// </summary>
		[ObservableProperty]
		private double _oilBathTemperature = 0;

		/// <summary>
		/// 冷凝温度
		/// </summary>
		[ObservableProperty]
		private double _condensationTemperature = 0;

		/// <summary>
		/// 旋转速度
		/// </summary>
		[ObservableProperty]
		private double _rotationSpeed = 0;

		/// <summary>
		/// 真空度
		/// </summary>
		[ObservableProperty]
		private double _vacuum = 0;

		/// <summary>
		/// 是否可以运行
		/// </summary>
		public bool CanRun => DeviceStatus == DeviceEnums.DeviceStatus.Idle && SelectedExperimentGroup != null;

		/// <summary>
		/// 是否可以暂停
		/// </summary>
		public bool CanPause => DeviceStatus == DeviceEnums.DeviceStatus.Running;

		/// <summary>
		/// 是否可以恢复
		/// </summary>
		public bool CanResume => DeviceStatus == DeviceEnums.DeviceStatus.Paused;

		/// <summary>
		/// 是否可以复位
		/// </summary>
		public bool CanReset => DeviceStatus == DeviceEnums.DeviceStatus.Error || DeviceStatus == DeviceEnums.DeviceStatus.EmergencyStopped;

		/// <summary>
		/// 是否可以初始化设备
		/// </summary>
		public bool CanInitialize => DeviceStatus == DeviceEnums.DeviceStatus.Idle || DeviceStatus == DeviceEnums.DeviceStatus.Error;

		/// <summary>
		/// 运行状态
		/// </summary>
		public string RunningState
		{
			get
			{
				switch (DeviceStatus)
				{
					case DeviceEnums.DeviceStatus.Running:
						return "运行中";
					case DeviceEnums.DeviceStatus.Paused:
						return "已暂停";
					case DeviceEnums.DeviceStatus.Idle:
						return "空闲";
					case DeviceEnums.DeviceStatus.Error:
						return "错误";
					case DeviceEnums.DeviceStatus.EmergencyStopped:
						return "紧急停止";
					case DeviceEnums.DeviceStatus.Standby:
						return "待机";
					case DeviceEnums.DeviceStatus.InMaintenance:
						return "维护中";
					case DeviceEnums.DeviceStatus.Initializing:
						return "正在初始化";
					default:
						return DeviceStatus.ToString();
				}
			}
		}

		/// <summary>
		/// 是否有实验
		/// </summary>
		public bool HasExperiments => SelectedExperimentGroup?.Experiments != null && SelectedExperimentGroup.Experiments.Any();

		/// <summary>
		/// 实验列表
		/// </summary>
		public ObservableCollection<ExperimentViewModel> Experiments => SelectedExperimentGroup?.Experiments;

		/// <summary>
		/// 日志消息
		/// </summary>
		[ObservableProperty]
		private ObservableCollection<string> _logMessages = new ObservableCollection<string>();

		/// <summary>
		/// 真空度（mbar）
		/// </summary>
		public double VacuumLevel => Vacuum * 1000;

		/// <summary>
		/// 可用的设备模式列表
		/// </summary>
		[ObservableProperty]
		private ObservableCollection<DeviceEnums.DeviceMode> _availableDeviceModes = new ObservableCollection<DeviceEnums.DeviceMode>();

		#endregion

		#region 配方详情相关属性

		/// <summary>
		/// 当前选中实验的配方
		/// </summary>
		[ObservableProperty]
		private RecipeDefinition _selectedRecipe;

		#endregion

		public MainOperationViewModel(
			ILogger<MainOperationViewModel> logger,
			IRecipeAppService recipeAppService,
			IMessageService messageService,
			IDeviceParameterDomainService deviceParameterService,
			ITaskSchedulingAppService taskSchedulingAppService,
			IDeviceAppService deviceAppService,
			IExperimentProcessAppService experimentProcessAppService,
			IExperimentRepository experimentRepository,
			IDeviceStatusService deviceStatusService)
		{
			_logger = logger;
			_recipeAppService = recipeAppService;
			_messageService = messageService;
			_deviceParameterService = deviceParameterService;
			_taskSchedulingAppService = taskSchedulingAppService;
			_deviceAppService = deviceAppService;
			_experimentProcessAppService = experimentProcessAppService;
			_experimentRepository = experimentRepository;
			_deviceStatusService = deviceStatusService;

			// 初始化命令
			ValidateRecipeCommand = new RelayCommand(async () => await ValidateRecipesAsync());
			ValidateExperimentGroupCommand = new RelayCommand(async () => await ValidateExperimentGroupAsync());
			RefreshExperimentGroupsCommand = new RelayCommand(async () => await RefreshExperimentGroupsAsync());
			DecomposeExperimentGroupCommand = new RelayCommand(async () => await DecomposeExperimentGroupAsync());

			// 初始化令牌源
			_statusUpdateCts = new CancellationTokenSource();

			// 订阅实验阶段和子阶段变更事件
			_experimentProcessAppService.ExperimentStageChanged += OnExperimentStageChanged;
			_experimentProcessAppService.ExperimentSubStageChanged += OnExperimentSubStageChanged;

			// 订阅设备模式和状态变更事件
			_deviceAppService.DeviceModeChanged += HandleDeviceModeChanged;
			_deviceAppService.DeviceStatusChanged += HandleDeviceStatusChanged;

			// 加载初始数据
			_ = InitializeAsync();
		}

		/// <summary>
		/// 初始化
		/// </summary>
		public async Task InitializeAsync()
		{
			try
			{
				IsLoading = true;
				_logger?.LogInformation("开始初始化实验操作界面...");

				// 启动设备状态监控
				await _deviceAppService.StartMonitoringAsync();

				// 获取当前设备模式和状态
				DeviceMode = await _deviceAppService.GetCurrentDeviceModeAsync();
				DeviceStatus = await _deviceAppService.GetDeviceStatusAsync();

				// 加载可用的设备模式
				await LoadAvailableDeviceModesAsync();

				// 加载实验组列表
				await LoadExperimentGroupsAsync();

				// 初始化当前实验阶段和子阶段
				CurrentExperimentId = _experimentProcessAppService.CurrentExperimentId;
				CurrentExperimentStage = _experimentProcessAppService.CurrentStage;
				CurrentExperimentSubStage = _experimentProcessAppService.CurrentSubStage;

				// 启动设备状态监控
				StartDeviceStatusMonitoring();

				_logger?.LogInformation("实验操作界面初始化完成");
			}
			catch (Exception ex)
			{
				_logger?.LogError(ex, "初始化实验操作界面失败");
			}
			finally
			{
				IsLoading = false;
			}
		}

		/// <summary>
		/// 添加日志消息
		/// </summary>
		private void AddLogMessage(string message)
		{
			LogMessages.Insert(0, $"[{DateTime.Now:HH:mm:ss}] {message}");

			// 保持日志数量在合理范围内
			while (LogMessages.Count > 100)
			{
				LogMessages.RemoveAt(LogMessages.Count - 1);
			}
		}

		/// <summary>
		/// 加载实验组
		/// </summary>
		private async Task LoadExperimentGroupsAsync()
		{
			try
			{
				// 保存当前选中的实验组ID
				Guid? selectedExperimentGroupId = SelectedExperimentGroup?.GroupId;

				var groups = await _recipeAppService.GetAllExperimentGroupsAsync();

				ExperimentGroups.Clear();
				foreach (var group in groups)
				{
					ExperimentGroups.Add(new ExperimentGroupViewModel(group));
				}

				// 恢复选中的实验组
				if (selectedExperimentGroupId.HasValue)
				{
					var previouslySelectedGroup = ExperimentGroups.FirstOrDefault(g => g.GroupId == selectedExperimentGroupId);
					if (previouslySelectedGroup != null)
					{
						SelectedExperimentGroup = previouslySelectedGroup;
						_logger.LogInformation($"已恢复选中的实验组: {previouslySelectedGroup.GroupName}");
					}
				}

				_logger.LogInformation($"已加载 {ExperimentGroups.Count} 个实验组");
				AddLogMessage($"已加载 {ExperimentGroups.Count} 个实验组");
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "加载实验组时发生错误");
				AddLogMessage($"加载实验组失败: {ex.Message}");
				throw;
			}
		}

		/// <summary>
		/// 选中实验组变更处理
		/// </summary>
		partial void OnSelectedExperimentGroupChanged(ExperimentGroupViewModel value)
		{
			if (value != null)
			{
				_logger.LogInformation($"已选择实验组: {value.GroupName}");
				AddLogMessage($"已选择实验组: {value.GroupName}");

				// 如果实验组中没有实验，则自动分解实验组为实验列表
				if (value.Experiments == null || !value.Experiments.Any())
				{
					if (DecomposeExperimentGroupCommand != null)
					{
						DecomposeExperimentGroupCommand.Execute(null);
					}
					else
					{
						_logger.LogWarning("分解实验组命令未初始化，无法自动分解实验组");
						AddLogMessage("分解实验组命令未初始化，请手动点击分解按钮");
					}
				}
				else
				{
					_logger.LogInformation($"实验组已包含 {value.Experiments.Count} 个实验，无需重新分解");
					AddLogMessage($"实验组已包含 {value.Experiments.Count} 个实验");

					// 选中第一个实验
					if (value.Experiments.Any())
					{
						SelectedExperiment = value.Experiments.First();
					}
				}

				// 通知属性变更
				OnPropertyChanged(nameof(HasExperiments));
				OnPropertyChanged(nameof(Experiments));
				OnPropertyChanged(nameof(CanRun));
				RunCommand.NotifyCanExecuteChanged(); // 确保命令状态更新
			}
			else
			{
				SelectedExperiment = null;
				OnPropertyChanged(nameof(HasExperiments));
				OnPropertyChanged(nameof(Experiments));
				OnPropertyChanged(nameof(CanRun));
				RunCommand.NotifyCanExecuteChanged(); // 确保命令状态更新
			}
		}

		/// <summary>
		/// 选中实验变更处理
		/// </summary>
		partial void OnSelectedExperimentChanged(ExperimentViewModel value)
		{
			if (value != null)
			{
				_logger.LogInformation($"已选择实验: {value.ExperimentName}");
				AddLogMessage($"已选择实验: {value.ExperimentName}");

				// 加载实验对应的配方
				LoadRecipeForExperiment(value);

				// 更新按钮状态
				OnPropertyChanged(nameof(CanRun));
				RunCommand.NotifyCanExecuteChanged(); // 显式通知命令重新评估可执行状态
			}
			else
			{
				SelectedRecipe = null;
				// 更新按钮状态
				OnPropertyChanged(nameof(CanRun));
				RunCommand.NotifyCanExecuteChanged(); // 显式通知命令重新评估可执行状态
			}
		}

		/// <summary>
		/// 加载实验对应的配方
		/// </summary>
		private async void LoadRecipeForExperiment(ExperimentViewModel experiment)
		{
			try
			{
				if (experiment == null)
				{
					SelectedRecipe = null;
					return;
				}

				IsLoading = true;

				// 获取实验对应的配方
				var recipe = await _recipeAppService.GetRecipeByIdAsync(experiment.Experiment.RecipeId);

				if (recipe != null)
				{
					SelectedRecipe = recipe;

					// 重要：将配方参数复制到实验的执行参数中，确保UI能正确显示
					if (experiment.Experiment.ExecutionParameters == null && recipe.RotovapParameters != null)
					{
						experiment.Experiment.ExecutionParameters = recipe.RotovapParameters.Clone();
						_logger.LogInformation("已将配方参数复制到实验执行参数中");
					}
					else if (experiment.Experiment.ExecutionParameters == null)
					{
						_logger.LogWarning("配方参数为空，无法复制到实验执行参数中");
						experiment.Experiment.ExecutionParameters = new RotovapParameters();
					}

					// 确保Recipe属性被设置，这样ExperimentName和ExperimentDescription才能正确显示
					if (experiment.Experiment.Recipe == null)
					{
						experiment.Experiment.Recipe = recipe;
						_logger.LogInformation("已设置实验的Recipe属性，确保实验名称和描述能正确显示");
					}

					_logger.LogInformation($"已加载配方: {recipe.ExperimentName}");
				}
				else
				{
					SelectedRecipe = null;
					_logger.LogWarning($"未找到实验 {experiment.ExperimentId} 对应的配方");
					AddLogMessage($"未找到实验对应的配方");
				}
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"加载实验的配方时发生错误");
				AddLogMessage($"加载配方失败: {ex.Message}");
				SelectedRecipe = null;
			}
			finally
			{
				IsLoading = false;
			}
		}

		/// <summary>
		/// 验证配方命令
		/// </summary>
		public ICommand ValidateRecipeCommand { get; }

		/// <summary>
		/// 验证实验组命令
		/// </summary>
		public ICommand ValidateExperimentGroupCommand { get; }

		/// <summary>
		/// 验证配方（已废弃，保留兼容性）
		/// </summary>
		private async Task ValidateRecipesAsync()
		{
			await _messageService.ShowInfoAsync("此功能已更新，请使用'验证实验组'按钮进行验证。", "功能已更新");
		}

		/// <summary>
		/// 验证实验组
		/// </summary>
		private async Task ValidateExperimentGroupAsync()
		{
			try
			{
				if (SelectedExperimentGroup == null)
				{
					await _messageService.ShowWarningAsync("请先选择一个实验组", "无法验证");
					return;
				}

				_logger.LogInformation($"验证实验组: {SelectedExperimentGroup.GroupName}");
				AddLogMessage($"开始验证实验组: {SelectedExperimentGroup.GroupName}");

				IsLoading = true;

				// 调用应用服务验证实验组
				var validationResult = await _taskSchedulingAppService.ValidateExperimentGroupAppAsync(SelectedExperimentGroup.GroupId.ToString());

				if (validationResult.IsValid)
				{
					await _messageService.ShowInfoAsync("实验组验证通过，可以安全运行。", "验证成功");
					AddLogMessage("验证成功: 实验组验证通过");
				}
				else
				{
					var errorMessage = string.Join("\n", validationResult.Errors);
					await _messageService.ShowWarningAsync($"实验组验证失败:\n{errorMessage}", "验证失败");
					AddLogMessage($"验证失败: {errorMessage}");
				}
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "验证实验组时发生错误");
				await _messageService.ShowErrorAsync($"验证实验组时发生错误: {ex.Message}", "验证失败");
				AddLogMessage($"验证失败: {ex.Message}");
			}
			finally
			{
				IsLoading = false;
			}
		}

		/// <summary>
		/// 刷新实验组命令
		/// </summary>
		public ICommand RefreshExperimentGroupsCommand { get; }

		/// <summary>
		/// 刷新实验组
		/// </summary>
		private async Task RefreshExperimentGroupsAsync()
		{
			try
			{
				_logger.LogInformation("刷新实验组列表");
				AddLogMessage("开始刷新实验组列表");

				IsLoading = true;

				// 重新加载实验组
				await LoadExperimentGroupsAsync();

				await _messageService.ShowInfoAsync("实验组列表已更新", "刷新成功");
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "刷新实验组时发生错误");
				await _messageService.ShowErrorAsync($"刷新实验组时发生错误: {ex.Message}", "刷新失败");
				AddLogMessage($"刷新失败: {ex.Message}");
			}
			finally
			{
				IsLoading = false;
			}
		}

		/// <summary>
		/// 分解实验组命令
		/// </summary>
		public ICommand DecomposeExperimentGroupCommand { get; }

		/// <summary>
		/// 分解实验组为实验列表
		/// </summary>
		private async Task DecomposeExperimentGroupAsync()
		{
			try
			{
				if (SelectedExperimentGroup == null)
				{
					_logger.LogWarning("无法分解实验组：未选择实验组");
					return;
				}

				_logger.LogInformation($"开始分解实验组: {SelectedExperimentGroup.GroupName}");
				AddLogMessage($"开始分解实验组: {SelectedExperimentGroup.GroupName}");

				IsLoading = true;

				// 调用应用服务分解实验组，但不保存到数据库
				var experiments = await _taskSchedulingAppService.DecomposeExperimentGroupForUIAsync(SelectedExperimentGroup.GroupId);

				// 更新实验组中的实验列表
				if (experiments != null && experiments.Any())
				{
					// 清空原有实验列表
					SelectedExperimentGroup.Experiments.Clear();

					// 添加新的实验
					foreach (var experiment in experiments)
					{
						// 确保Recipe属性不为空，这样ExperimentName和ExperimentDescription才能正确显示
						if (experiment.Recipe == null && experiment.RecipeId != Guid.Empty)
						{
							var recipe = await _recipeAppService.GetRecipeByIdAsync(experiment.RecipeId);
							if (recipe != null)
							{
								experiment.Recipe = recipe;
							}
						}

						// 确保ExecutionParameters不为空
						if (experiment.ExecutionParameters == null && experiment.Recipe?.RotovapParameters != null)
						{
							experiment.ExecutionParameters = experiment.Recipe.RotovapParameters.Clone();
						}
						else if (experiment.ExecutionParameters == null)
						{
							experiment.ExecutionParameters = new RotovapParameters();
						}

						// 添加新的实验视图模型
						SelectedExperimentGroup.AddOrUpdateExperiment(experiment);
					}

					_logger.LogInformation($"实验组分解完成，共 {experiments.Count} 个实验");
					AddLogMessage($"实验组分解完成，共 {experiments.Count} 个实验");

					// 选中第一个实验
					if (SelectedExperimentGroup.Experiments.Any())
					{
						SelectedExperiment = SelectedExperimentGroup.Experiments.First();
					}
				}
				else
				{
					_logger.LogWarning("实验组分解结果为空");
					AddLogMessage("实验组分解结果为空，未生成实验");
					await _messageService.ShowWarningAsync("实验组分解结果为空，未生成实验", "分解结果");
				}

				// 通知属性变更
				OnPropertyChanged(nameof(HasExperiments));
				OnPropertyChanged(nameof(Experiments));
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "分解实验组时发生错误");
				AddLogMessage($"分解实验组失败: {ex.Message}");
				await _messageService.ShowErrorAsync($"分解实验组时发生错误: {ex.Message}", "分解失败");
			}
			finally
			{
				IsLoading = false;
			}
		}

		#region 设备模式相关命令和方法

		/// <summary>
		/// 切换到单机自动模式命令
		/// </summary>
		[RelayCommand]
		private async Task SwitchToAutomaticModeAsync()
		{
			await SwitchDeviceModeAsync(DeviceEnums.DeviceMode.SingleMachineAutomatic);
		}

		/// <summary>
		/// 切换到联机自动模式命令
		/// </summary>
		[RelayCommand]
		private async Task SwitchToOnlineAutomaticModeAsync()
		{
			await SwitchDeviceModeAsync(DeviceEnums.DeviceMode.OnlineAutomatic);
		}

		/// <summary>
		/// 切换到手动模式命令
		/// </summary>
		[RelayCommand]
		private async Task SwitchToManualModeAsync()
		{
			await SwitchDeviceModeAsync(DeviceEnums.DeviceMode.Manual);
		}

		/// <summary>
		/// 切换到维护模式命令
		/// </summary>
		[RelayCommand]
		private async Task SwitchToMaintenanceModeAsync()
		{
			await SwitchDeviceModeAsync(DeviceEnums.DeviceMode.Maintenance);
		}

		/// <summary>
		/// 切换设备模式
		/// </summary>
		private async Task SwitchDeviceModeAsync(DeviceEnums.DeviceMode targetMode)
		{
			try
			{
				if (DeviceMode == targetMode)
				{
					_logger.LogInformation($"设备已经处于 {targetMode} 模式");
					return;
				}

				// 检查模式是否可用
				if (!await _deviceAppService.IsModeAvailableAsync(targetMode))
				{
					await _messageService.ShowWarningAsync("模式不可用", $"设备模式 {GetDeviceModeDescription(targetMode)} 当前不可用");
					return;
				}

				IsLoading = true;
				_logger.LogInformation($"正在切换设备模式到: {targetMode}");

				var result = await _deviceAppService.SetDeviceModeAsync(targetMode);

				if (!result.Success)
				{
					await _messageService.ShowErrorAsync("模式切换失败", result.Message);
				}
				else
				{
					await _messageService.ShowInfoAsync("模式切换", $"设备已切换到 {GetDeviceModeDescription(targetMode)} 模式");
				}
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"切换设备模式到 {targetMode} 时发生错误");
				await _messageService.ShowErrorAsync("模式切换失败", $"切换设备模式时发生错误: {ex.Message}");
			}
			finally
			{
				IsLoading = false;
			}
		}

		/// <summary>
		/// 获取设备模式的描述文本
		/// </summary>
		private string GetDeviceModeDescription(DeviceEnums.DeviceMode mode)
		{
			return mode switch
			{
				DeviceEnums.DeviceMode.SingleMachineAutomatic => "单机自动",
				DeviceEnums.DeviceMode.OnlineAutomatic => "联机自动",
				DeviceEnums.DeviceMode.Manual => "手动",
				DeviceEnums.DeviceMode.Maintenance => "维护",
				_ => mode.ToString()
			};
		}

		/// <summary>
		/// 加载可用的设备模式
		/// </summary>
		private async Task LoadAvailableDeviceModesAsync()
		{
			try
			{
				// 从设备应用服务获取可用的模式
				var availableModes = await _deviceAppService.GetAvailableModesAsync();

				AvailableDeviceModes.Clear();
				foreach (var mode in availableModes)
				{
					AvailableDeviceModes.Add(mode);
				}

				_logger.LogInformation($"已加载可用的设备模式: {string.Join(", ", availableModes)}");
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "加载可用设备模式时发生错误");

				// 出错时添加默认模式
				AvailableDeviceModes.Clear();
				AvailableDeviceModes.Add(DeviceEnums.DeviceMode.SingleMachineAutomatic);
				AvailableDeviceModes.Add(DeviceEnums.DeviceMode.OnlineAutomatic);
				AvailableDeviceModes.Add(DeviceEnums.DeviceMode.Manual);
				AvailableDeviceModes.Add(DeviceEnums.DeviceMode.Maintenance);
			}
		}

		/// <summary>
		/// 处理设备模式变更事件
		/// </summary>
		private void HandleDeviceModeChanged(object sender, DeviceModeChangedEventArgs e)
		{
			try
			{
				// 在UI线程上更新设备模式
				DeviceMode = e.Mode;
				_logger.LogInformation($"UI收到设备模式变更通知: {e.Mode}");
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "处理设备模式变更事件时发生错误");
			}
		}

		/// <summary>
		/// 处理设备状态变更事件
		/// </summary>
		private void HandleDeviceStatusChanged(object sender, DeviceStatusChangedEventArgs e)
		{
			try
			{
				// 在UI线程上更新设备状态
				DeviceStatus = e.Status;
				_logger.LogInformation($"UI收到设备状态变更通知: {e.Status}");
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "处理设备状态变更事件时发生错误");
			}
		}

		#endregion

		/// <summary>
		/// 处理实验阶段变更事件
		/// </summary>
		private void OnExperimentStageChanged(object sender, ExperimentStageChangedEventArgs e)
		{
			_logger.LogInformation($"UI: 实验 {e.ExperimentId} 阶段变更为 {e.Stage}");

			// 更新 UI 属性
			CurrentExperimentId = e.ExperimentId;
			CurrentExperimentStage = e.Stage;
			CurrentStageProgress = 0; // 重置进度

			// 更新实验列表中对应实验的状态
			UpdateExperimentInList(e.ExperimentId);
		}

		/// <summary>
		/// 处理实验子阶段变更事件
		/// </summary>
		private void OnExperimentSubStageChanged(object sender, ExperimentSubStageChangedEventArgs e)
		{
			_logger.LogInformation($"UI: 实验 {e.ExperimentId} 子阶段变更为 {e.SubStage}");

			// 更新 UI 属性
			CurrentExperimentId = e.ExperimentId;
			CurrentExperimentStage = e.Stage;
			CurrentExperimentSubStage = e.SubStage;

			// 更新子阶段进度
			UpdateStageProgress(e.Stage, e.SubStage);

			// 更新实验列表中对应实验的状态
			UpdateExperimentInList(e.ExperimentId);
		}

		/// <summary>
		/// 根据阶段和子阶段更新进度
		/// </summary>
		private void UpdateStageProgress(ExperimentStage stage, ExperimentSubStage subStage)
		{
			// 简单进度计算逻辑，可以根据实际需求定制
			switch (stage)
			{
				case ExperimentStage.MaterialAndConditionPreparation:
					// 计算物料准备阶段进度
					switch (subStage)
					{
						case ExperimentSubStage.ControllingOilBathTemperature:
							CurrentStageProgress = 10;
							break;
						case ExperimentSubStage.ControllingCondensationTemperature:
							CurrentStageProgress = 25;
							break;
						case ExperimentSubStage.InstallingRotaryBottle:
							CurrentStageProgress = 40;
							break;
						case ExperimentSubStage.TransportingMaterialVial:
							CurrentStageProgress = 60;
							break;
						case ExperimentSubStage.PumpingLiquid:
							CurrentStageProgress = 80;
							break;
						case ExperimentSubStage.ReturningMaterialVial:
							CurrentStageProgress = 95;
							break;
						case ExperimentSubStage.Completed:
							CurrentStageProgress = 100;
							break;
					}
					break;

				case ExperimentStage.RotaryEvaporation:
					// 计算旋蒸阶段进度
					switch (subStage)
					{
						case ExperimentSubStage.VacuumBuilding:
							CurrentStageProgress = 10;
							break;
						case ExperimentSubStage.StartingRotation:
							CurrentStageProgress = 20;
							break;
						case ExperimentSubStage.MonitoringEvaporation:
							CurrentStageProgress = 45;
							break;
						case ExperimentSubStage.FinalCollection:
							CurrentStageProgress = 60;
							break;
						case ExperimentSubStage.ReturningCollectionBottle:
							CurrentStageProgress = 70;
							break;
						case ExperimentSubStage.CollectionInfoJudgment:
							CurrentStageProgress = 75;
							break;
						case ExperimentSubStage.PreparingNewEnvironment:
							CurrentStageProgress = 80;
							break;
						case ExperimentSubStage.CollectingCondensate:
							CurrentStageProgress = 85;
							break;
						case ExperimentSubStage.FinishingEvaporation:
							CurrentStageProgress = 95;
							break;
						case ExperimentSubStage.Completed:
							CurrentStageProgress = 100;
							break;
					}
					break;

				case ExperimentStage.EvaporationResidueProcessing:
					// 计算旋蒸残液处理进度
					switch (subStage)
					{
						case ExperimentSubStage.TransportingFlaskToWorkstation:
							CurrentStageProgress = 20;
							break;
						case ExperimentSubStage.SamplingResidues:
							CurrentStageProgress = 40;
							break;
						case ExperimentSubStage.CollectingResidues:
							CurrentStageProgress = 70;
							break;
						case ExperimentSubStage.ReturningFlaskToShelf:
							CurrentStageProgress = 90;
							break;
						case ExperimentSubStage.Completed:
							CurrentStageProgress = 100;
							break;
					}
					break;

				case ExperimentStage.CondensateProcessing:
					// 计算冷凝液处理进度
					switch (subStage)
					{
						case ExperimentSubStage.SamplingCondensate:
							CurrentStageProgress = 70;
							break;
						case ExperimentSubStage.Completed:
							CurrentStageProgress = 100;
							break;
					}
					break;

				case ExperimentStage.Cleaning:
					// 计算清洗阶段进度
					switch (subStage)
					{
						case ExperimentSubStage.CleaningCondenser:
							CurrentStageProgress = 40;
							break;
						case ExperimentSubStage.CleaningRotovapTubes:
							CurrentStageProgress = 80;
							break;
						case ExperimentSubStage.Completed:
							CurrentStageProgress = 100;
							break;
					}
					break;

				case ExperimentStage.Completed:
					CurrentStageProgress = 100;
					break;

				case ExperimentStage.Failed:
					CurrentStageProgress = 0;
					break;

				default:
					CurrentStageProgress = 0;
					break;
			}
		}

		/// <summary>
		/// 更新实验列表中的实验信息
		/// </summary>
		/// <param name="experimentId">实验ID</param>
		private async Task UpdateExperimentInList(Guid experimentId)
		{
			try
			{
				// 查找并加载实验信息
				var experiment = await _experimentRepository.GetByIdAsync(experimentId);
				if (experiment == null)
				{
					_logger.LogWarning($"无法更新实验列表：找不到实验 (ID: {experimentId})");
					return;
				}

				// 调用另一个重载方法完成实际更新
				await UpdateExperimentInList(experiment);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"更新实验 {experimentId} 信息时发生错误");
			}
		}

		/// <summary>
		/// 更新实验列表中的实验信息
		/// </summary>
		/// <param name="experiment">实验</param>
		/// <param name="experimentGroup">实验组</param>
		/// <returns></returns>
		private async Task UpdateExperimentInList(Experiment experiment, ExperimentGroupViewModel experimentGroup = null)
		{
			try
			{
				if (experiment == null)
				{
					_logger.LogWarning("无法更新实验列表：实验为空");
					return;
				}

				// 查找实验所在的实验组
				var targetGroup = experimentGroup ?? ExperimentGroups.FirstOrDefault(g => g.Experiments.Any(e => e.ExperimentId == experiment.ExperimentId));

				if (targetGroup == null)
				{
					_logger.LogWarning($"无法更新实验列表：找不到实验组 (实验ID: {experiment.ExperimentId})");
					return;
				}

				_logger.LogInformation($"更新实验 {experiment.ExperimentId} 在实验组 {targetGroup.GroupName} 中的状态: {experiment.Status}");

				// 查找此实验在组中的索引
				var existingExperiment = targetGroup.Experiments.FirstOrDefault(e => e.ExperimentId == experiment.ExperimentId);

				if (existingExperiment != null)
				{
					// 记录状态变化
					var oldStatus = existingExperiment.Status;

					// 更新现有实验的属性
					targetGroup.UpdateExperiment(experiment);

					// 状态变化时记录日志并刷新UI
					if (oldStatus != experiment.Status)
					{
						_logger.LogInformation($"实验 {experiment.ExperimentId} 状态从 {oldStatus} 变为 {experiment.Status}");

						// 强制刷新此实验在UI中的显示
						var index = targetGroup.Experiments.IndexOf(existingExperiment);
						if (index >= 0)
						{
							var temp = existingExperiment;
							targetGroup.Experiments.RemoveAt(index);
							targetGroup.Experiments.Insert(index, temp);
						}

						// 通知UI刷新
						OnPropertyChanged(nameof(Experiments));
						OnPropertyChanged(nameof(HasExperiments));
						OnPropertyChanged(nameof(ExperimentGroups));
					}
				}
				else
				{
					// 如果实验不存在于组中，则添加它
					_logger.LogInformation($"添加实验 {experiment.ExperimentId} 到实验组 {targetGroup.GroupName}");
					targetGroup.AddOrUpdateExperiment(experiment);

					// 通知UI刷新
					OnPropertyChanged(nameof(Experiments));
					OnPropertyChanged(nameof(HasExperiments));
					OnPropertyChanged(nameof(ExperimentGroups));
				}

				// 如果需要，更新实验组的状态
				await UpdateExperimentGroupStatus(targetGroup);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "更新实验列表时发生错误");
			}
		}

		/// <summary>
		/// 更新实验组状态
		/// </summary>
		/// <param name="experimentGroup">要更新的实验组</param>
		/// <returns></returns>
		private async Task UpdateExperimentGroupStatus(ExperimentGroupViewModel experimentGroup)
		{
			if (experimentGroup == null)
				return;

			try
			{
				// 更新实验组的状态和进度
				experimentGroup.UpdateStatus();

				// 如果实验组已完成或失败，获取最新的实验组信息（确保与数据库同步）
				if (experimentGroup.Status == ExperimentGroupStatus.Completed ||
					experimentGroup.Status == ExperimentGroupStatus.Failed)
				{
					// 使用任务调度服务获取最新的实验组信息
					var experiments = await _taskSchedulingAppService.GetExperimentsInGroupAsync(experimentGroup.GroupId);
					if (experiments != null && experiments.Any())
					{
						// 更新实验组内的实验
						foreach (var experiment in experiments)
						{
							await UpdateExperimentInList(experiment, experimentGroup);
						}
					}
				}

				// 通知UI
				OnPropertyChanged(nameof(ExperimentGroups));
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"更新实验组 {experimentGroup.GroupName} 状态时发生错误");
			}
		}

		#region 设备状态监控
		/// <summary>
		/// 启动设备状态监控
		/// </summary>
		public void StartDeviceStatusMonitoring()
		{
			if (_isMonitoring)
				return;

			try
			{
				_logger?.LogInformation("开始设备状态监控");

				// 确保事件处理程序只注册一次
				_deviceStatusService.DeviceStatusChanged -= OnDeviceStatusChanged;
				//_deviceStatusService.DeviceStatusChanged += OnDeviceStatusChanged;

				// 立即刷新一次设备状态
				_ = RefreshDeviceStatusAsync();

				_isMonitoring = true;
			}
			catch (Exception ex)
			{
				_logger?.LogError(ex, "启动设备状态监控失败");
			}
		}

		/// <summary>
		/// 停止设备状态监控
		/// </summary>
		public void StopDeviceStatusMonitoring()
		{
			if (!_isMonitoring)
				return;

			try
			{
				_logger?.LogInformation("停止设备状态监控");

				// 取消订阅设备状态变化事件
				_deviceStatusService.DeviceStatusChanged -= OnDeviceStatusChanged;

				_isMonitoring = false;
			}
			catch (Exception ex)
			{
				_logger?.LogError(ex, "停止设备状态监控失败");
			}
		}

		/// <summary>
		/// 设备状态变化事件处理
		/// </summary>
		private void OnDeviceStatusChanged(object sender, DeviceStatusEventArgs e)
		{
			if (!_isMonitoring || _isDisposed)
				return;

			try
			{
				_logger?.LogDebug($"接收到设备状态变化事件: DeviceId={e.DeviceId}, Status={e.Status}");

				// 使用UI线程调度器确保在UI线程上更新控件
				App.Current.Dispatcher.Invoke(() =>
				{
					// 处理油浴温度变化
					if (e.DeviceId == "OilBath_503_1" && e.Status is OilBathStatus oilBathStatus)
					{
						OilBathTemperature = oilBathStatus.CurrentTemperaturePV;
						_logger?.LogDebug($"已更新油浴温度: {oilBathStatus.CurrentTemperaturePV}°C");
					}
					//// 处理冷凝温度变化
					//else if (e.DeviceId == "TCU_502_1" && e.Status is TCUStatus tcuStatus)
					//{
					//	CondensationTemperature = tcuStatus.MainTemperature;
					//	_logger?.LogDebug($"已更新冷凝温度: {tcuStatus.MainTemperature}°C");
					//}
					// 处理旋转速度变化
					else if (e.DeviceId == "RotovapRotaryMotor" && e.Status is MotorStatus motorStatus)
					{
						RotationSpeed = motorStatus.Actual_V;
						_logger?.LogDebug($"已更新旋转速度: {motorStatus.Actual_V} rpm");
					}
					// 处理真空度变化
					else if (e.DeviceId == "CondenserPressure" && e.Status is double vacuum)
					{
						Vacuum = vacuum;
						OnPropertyChanged(nameof(VacuumLevel)); // 更新mbar单位的显示
						_logger?.LogDebug($"已更新真空度: {vacuum} bar");
					}
				});
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "处理设备状态变化事件失败");
			}
		}

		/// <summary>
		/// 刷新设备状态，可以在需要时手动调用
		/// </summary>
		[RelayCommand]
		public async Task RefreshDeviceStatusAsync()
		{
			if (!_isMonitoring || _isDisposed)
				return;

			try
			{
				// 获取各设备状态
				var oilBathStatus = await _deviceStatusService.GetOilBathStatusAsync("OilBath_503_1");
				var rotationSpeed = await GetRotaryMotorSpeedAsync();
				var vacuum = _deviceStatusService.GetCondenserPressure();

				// 使用UI线程调度器更新UI属性
				App.Current.Dispatcher.Invoke(() =>
				{
					OilBathTemperature = oilBathStatus.CurrentTemperaturePV;
					RotationSpeed = rotationSpeed;
					Vacuum = vacuum;
					OnPropertyChanged(nameof(VacuumLevel)); // 更新mbar单位的显示
				});

				_logger?.LogDebug("主操作视图设备状态刷新成功");
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "刷新设备状态失败");
			}
		}

		/// <summary>
		/// 重新初始化设备状态监控
		/// </summary>
		public void ReinitializeDeviceMonitoring()
		{
			_logger?.LogInformation("重新初始化设备状态监控");

			// 停止之前的监控
			StopDeviceStatusMonitoring();

			// 重置状态
			if (_isDisposed)
			{
				_isDisposed = false;
			}

			// 重新启动监控
			StartDeviceStatusMonitoring();
		}

		/// <summary>
		/// 获取旋转电机当前速度
		/// </summary>
		private async Task<double> GetRotaryMotorSpeedAsync()
		{
			try
			{
				var status = await _deviceStatusService.GetMotorStatusAsync("RotovapRotaryMotor");
				return status.Actual_V;
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "获取旋转电机速度失败");
				return 0;
			}
		}
		#endregion

		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (!_isDisposed)
			{
				if (disposing)
				{
					// 停止设备状态监控
					StopDeviceStatusMonitoring();

					// 取消订阅实验阶段事件
					if (_experimentProcessAppService != null)
					{
						_experimentProcessAppService.ExperimentStageChanged -= OnExperimentStageChanged;
						_experimentProcessAppService.ExperimentSubStageChanged -= OnExperimentSubStageChanged;
					}

					// 取消设备事件订阅
					if (_deviceAppService != null)
					{
						_deviceAppService.DeviceModeChanged -= HandleDeviceModeChanged;
						_deviceAppService.DeviceStatusChanged -= HandleDeviceStatusChanged;
						_ = _deviceAppService.StopMonitoringAsync();
					}
				}

				_isDisposed = true;
			}
		}

		#region 命令

		/// <summary>
		/// 运行命令
		/// </summary>
		[RelayCommand(CanExecute = nameof(CanRun))]
		private async Task RunAsync()
		{
			try
			{
				// 检查设备是否处于空闲状态
				if (DeviceStatus != DeviceEnums.DeviceStatus.Idle)
				{
					await _messageService.ShowWarningAsync("设备当前状态不允许运行实验", "无法运行");
					return;
				}

				// 检查设备是否处于单机自动模式
				if (DeviceMode != DeviceEnums.DeviceMode.SingleMachineAutomatic)
				{
					var switchModeResult = await _messageService.ShowConfirmAsync(
						"设备当前不处于单机自动模式，运行实验组需要切换到单机自动模式。是否立即切换？",
						"需要切换模式");

					if (switchModeResult)
					{
						// 尝试切换到单机自动模式
						var setModeResult = await _deviceAppService.SetDeviceModeAsync(DeviceEnums.DeviceMode.SingleMachineAutomatic);
						if (!setModeResult.Success)
						{
							await _messageService.ShowErrorAsync($"切换到单机自动模式失败: {setModeResult.Message}", "模式切换失败");
							return;
						}
						// 切换成功后短暂延迟，确保状态已更新
						await Task.Delay(500);
					}
					else
					{
						return; // 用户取消切换，终止运行
					}
				}

				var result = await _messageService.ShowConfirmAsync(
					$"确定要运行实验组 '{SelectedExperimentGroup.GroupName}' 吗？该操作将运行实验组中的所有实验。",
					"确认运行");

				if (!result)
				{
					return;
				}

				_logger.LogInformation($"开始运行实验组: {SelectedExperimentGroup.GroupId}");
				AddLogMessage($"开始运行实验组: {SelectedExperimentGroup.GroupId}");

				// 更新UI状态为正在加载
				//IsLoading = true;

				// 调用任务调度服务启动实验组
				var operationResult = await _taskSchedulingAppService.StartExperimentGroupAsync(SelectedExperimentGroup.ExperimentGroup);

				// 检查实验组启动结果
				if (!operationResult.Success)
				{
					IsLoading = false;
					await _messageService.ShowErrorAsync($"启动实验组失败:\n{operationResult.Message}", "运行失败");
					AddLogMessage($"运行失败: {operationResult.Message}");
					return;
				}

				// 注意：不再直接更新设备状态，而是由领域服务通过事件通知来更新
				// 只更新UI上不影响业务逻辑的元素
				Progress = 0;
				RemainingTime = 100; // 假设总时间为100分钟
				IsLoading = false;

				AddLogMessage("实验组已进入执行阶段");

				await _messageService.ShowInfoAsync($"实验组 '{SelectedExperimentGroup.GroupName}' 已开始运行", "实验组已启动");
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "运行实验组时发生错误");
				await _messageService.ShowErrorAsync($"启动实验组时发生错误: {ex.Message}", "运行失败");
				AddLogMessage($"运行失败: {ex.Message}");

				// 恢复UI状态
				IsLoading = false;
			}
		}

		/// <summary>
		/// 暂停命令
		/// </summary>
		[RelayCommand(CanExecute = nameof(CanPause))]
		private async Task PauseAsync()
		{
			try
			{
				if (DeviceStatus != DeviceEnums.DeviceStatus.Running)
				{
					await _messageService.ShowWarningAsync("设备当前状态不允许暂停", "无法暂停");
					return;
				}

				var result = await _messageService.ShowConfirmAsync(
					"确定要暂停当前实验吗？",
					"确认暂停");

				if (!result)
				{
					return;
				}

				_logger.LogInformation("暂停实验");
				AddLogMessage("暂停实验");

				// 更新UI状态
				DeviceStatus = DeviceEnums.DeviceStatus.Paused;

				// 在实际应用中，这里应该调用设备控制服务暂停实验
				// await _deviceControlService.PauseExperimentAsync();

				// 模拟实验暂停
				await Task.Delay(1000);

				await _messageService.ShowInfoAsync("实验已暂停，可以通过点击'继续'按钮恢复运行", "实验已暂停");
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "暂停实验时发生错误");
				await _messageService.ShowErrorAsync($"暂停实验时发生错误: {ex.Message}", "暂停失败");
				AddLogMessage($"暂停失败: {ex.Message}");
			}
		}

		/// <summary>
		/// 继续命令
		/// </summary>
		[RelayCommand(CanExecute = nameof(CanResume))]
		private async Task ResumeAsync()
		{
			try
			{
				if (DeviceStatus != DeviceEnums.DeviceStatus.Paused)
				{
					await _messageService.ShowWarningAsync("设备当前状态不允许继续运行", "无法继续");
					return;
				}

				_logger.LogInformation("继续实验");
				AddLogMessage("继续实验");

				// 更新UI状态
				DeviceStatus = DeviceEnums.DeviceStatus.Running;

				// 在实际应用中，这里应该调用设备控制服务恢复实验
				// await _deviceControlService.ResumeExperimentAsync();

				// 模拟实验恢复
				await Task.Delay(1000);

				await _messageService.ShowInfoAsync("实验已恢复运行", "实验已恢复");
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "恢复实验时发生错误");
				await _messageService.ShowErrorAsync($"恢复实验时发生错误: {ex.Message}", "恢复失败");
				AddLogMessage($"恢复失败: {ex.Message}");

				// 确保UI状态一致
				DeviceStatus = DeviceEnums.DeviceStatus.Paused;
			}
		}

		/// <summary>
		/// 复位命令
		/// </summary>
		[RelayCommand(CanExecute = nameof(CanReset))]
		private async Task ResetAsync()
		{
			try
			{
				if (DeviceStatus != DeviceEnums.DeviceStatus.Error && DeviceStatus != DeviceEnums.DeviceStatus.EmergencyStopped)
				{
					await _messageService.ShowWarningAsync("设备当前状态不需要复位", "无法复位");
					return;
				}

				var result = await _messageService.ShowConfirmAsync(
					"确定要复位设备吗？此操作将中断当前实验。",
					"确认复位");

				if (!result)
				{
					return;
				}

				_logger.LogInformation("复位设备");
				AddLogMessage("开始复位设备");

				// 更新UI状态为正在复位
				IsLoading = true;

				// 在实际应用中，这里应该调用设备服务复位设备
				// await _deviceAppService.ResetDeviceAsync();

				// 模拟设备复位
				await Task.Delay(3000);

				// 更新UI状态为空闲
				IsLoading = false;
				DeviceStatus = DeviceEnums.DeviceStatus.Idle;
				CurrentStep = DeviceEnums.MainStep.None;
				Progress = 0;
				RemainingTime = 0;

				await _messageService.ShowInfoAsync("设备已成功复位", "复位完成");
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "复位设备时发生错误");
				await _messageService.ShowErrorAsync($"复位设备时发生错误: {ex.Message}", "复位失败");
				AddLogMessage($"复位失败: {ex.Message}");
				IsLoading = false;
			}
		}

		/// <summary>
		/// 设备初始化命令
		/// </summary>
		[RelayCommand(CanExecute = nameof(CanInitialize))]
		private async Task InitializeDevicesAsync()
		{
			try
			{
				_logger.LogInformation("开始执行设备初始化");
				//IsLoading = true;

				// 显示确认对话框
				var confirm = await _messageService.ShowConfirmAsync("设备初始化", "确定要执行设备初始化操作吗？这将使所有设备回零并重置状态。");
				if (!confirm)
				{
					_logger.LogInformation("用户取消了设备初始化");
					IsLoading = false;
					return;
				}

				// 调用应用服务执行设备初始化
				var result = await _experimentProcessAppService.InitializeDevicesAsync();

				if (result.Success)
				{
					await _messageService.ShowInfoAsync("设备初始化", "设备初始化成功完成！");
					_logger.LogInformation("设备初始化成功");
				}
				else
				{
					await _messageService.ShowErrorAsync("设备初始化", $"设备初始化失败: {result.Message}");
					_logger.LogError("设备初始化失败: {Message}", result.Message);
				}
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "执行设备初始化时发生错误");
				await _messageService.ShowErrorAsync("错误", $"执行设备初始化时发生错误: {ex.Message}");
			}
			finally
			{
				IsLoading = false;
			}
		}

		#endregion
	}
}
